{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 字符串的应用\n",
    "\n",
    "这里涉及数据结构内容，可以查看第四章相关知识。这里主要以看例子学习为主。查看下面的例子，学会应该"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#-- 常见字符串常量和表达式\n",
    "S1 = ''                                  # 空字符串\n",
    "S2 = \"spam’s\"                            # 双引号和单引号相同\n",
    "S3 = \"s\\np\\ta\\x00m\"                      # 转义字符\n",
    "S4 = \"\"\"spam\"\"\"                          # 三重引号字符串，一般用于函数说明\n",
    "S5 = r'\\temp'                            # Raw字符串，不会进行转义，抑制转义\n",
    "S6 = b'Spam'                             # Python3中的字节字符串\n",
    "S7 = u'spam'                             # Python2.6中的Unicode字符串\n",
    "print(S6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字节字符串\n",
    "字符串是字符序列，它是一种抽象的概念，不能直接存储在硬盘；字节字符串是字节序列，它可以直接存储在硬盘。它们之间的映射被称为编码/解码\n",
    "\n",
    "\n",
    "### 字符串操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 字符串操作\n",
    "s1 = \"ABCD\"\n",
    "s2 = \"12345\"\n",
    "print(s1+s2)\n",
    "print(s1*3)\n",
    "print(s1[0], s2[1:3], len(s1))\n",
    "\n",
    "# 字符串迭代，成员关系\n",
    "print('----成员关系----')\n",
    "for x in s1:\n",
    "    print(x)\n",
    "\n",
    "print('----字符串的合并----')\n",
    "# 字符串输出，结果：a,b,c\n",
    "print(','.join(['a', 'b', 'c']))\n",
    "\n",
    "print('----字符串拆分----')\n",
    "# 字符串输出，结果：a,b,c\n",
    "print(s2.split('3'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 练习：把 http://www.cnblogs.com/fat39/p/7159881.html 变成 http://www.cnblogs.com\\fat39\\p\\7159881.html\n",
    "s = \"http://www.cnblogs.com/fat39/p/7159881.html\"\n",
    "s = s.split(??)\n",
    "tmp_url = s[??].split(??)\n",
    "print(s[??]+\"//\"+???.join(tmp_url))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 格式化输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "print('这个女孩真 %s，我很喜欢' % '漂亮')               # 字符串格式化表达式\n",
    "print('{0} 比 {1} 高'.format('姚明', '郭敬明'))       # 字符串格式化方法，位置区分\n",
    "print('{a} {b} {a}'.format(b='左',a='右'))          # 关键词区分 "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "更详细内容： https://www.cnblogs.com/fat39/p/7159881.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#-- Python中的字符串格式化实现1--字符串格式化表达式\n",
    "    \"\"\"\n",
    "    基于C语言的'print'模型，并且在大多数的现有的语言中使用。\n",
    "    通用结构：%[(name)][flag][width].[precision]typecode\n",
    "    \"\"\"\n",
    "    \"this is %d %s bird\" % (1, 'dead')                          # 一般的格式化表达式\n",
    "    \"%s---%s---%s\" % (42, 3.14, [1, 2, 3])                      # 字符串输出：'42---3.14---[1, 2, 3]'\n",
    "    \"%d...%6d...%-6d...%06d\" % (1234, 1234, 1234, 1234)         # 对齐方式及填充：\"1234...  1234...1234  ...001234\"\n",
    "    x = 1.23456789\n",
    "    \"%e | %f | %g\" % (x, x, x)                                  # 对齐方式：\"1.234568e+00 | 1.234568 | 1.23457\"\n",
    "    \"%6.2f*%-6.2f*%06.2f*%+6.2f\" % (x, x, x, x)                 # 对齐方式：'  1.23*1.23  *001.23* +1.23'\n",
    "    \"%(name1)d---%(name2)s\" % {\"name1\":23, \"name2\":\"value2\"}    # 基于字典的格式化表达式\n",
    "    \"%(name)s is %(age)d\" % vars()                              # vars()函数调用返回一个字典，包含了所有本函数调用时存在的变量\n",
    "    \n",
    "#-- Python中的字符串格式化实现2--字符串格式化调用方法\n",
    "    # 普通调用\n",
    "    \"{0}, {1} and {2}\".format('spam', 'ham', 'eggs')            # 基于位置的调用\n",
    "    \"{motto} and {pork}\".format(motto = 'spam', pork = 'ham')   # 基于Key的调用\n",
    "    \"{motto} and {0}\".format('ham', motto = 'spam')             # 混合调用\n",
    "    # 添加键 属性 偏移量 (import sys)\n",
    "    \"my {1[spam]} runs {0.platform}\".format(sys, {'spam':'laptop'})                 # 基于位置的键和属性\n",
    "    \"{config[spam]} {sys.platform}\".format(sys = sys, config = {'spam':'laptop'})   # 基于Key的键和属性\n",
    "    \"first = {0[0]}, second = {0[1]}\".format(['A', 'B', 'C'])                       # 基于位置的偏移量\n",
    "    # 具体格式化\n",
    "    \"{0:e}, {1:.3e}, {2:g}\".format(3.14159, 3.14159, 3.14159)   # 输出'3.141590e+00, 3.142e+00, 3.14159'\n",
    "    \"{fieldname:format_spec}\".format(......)\n",
    "    # 说明:\n",
    "    \"\"\"\n",
    "        fieldname是指定参数的一个数字或关键字, 后边可跟可选的\".name\"或\"[index]\"成分引用\n",
    "        format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]\n",
    "        fill        ::=  <any character>              #填充字符\n",
    "        align       ::=  \"<\" | \">\" | \"=\" | \"^\"        #对齐方式\n",
    "        sign        ::=  \"+\" | \"-\" | \" \"              #符号说明\n",
    "        width       ::=  integer                      #字符串宽度\n",
    "        precision   ::=  integer                      #浮点数精度\n",
    "        type        ::=  \"b\" | \"c\" | \"d\" | \"e\" | \"E\" | \"f\" | \"F\" | \"g\" | \"G\" | \"n\" | \"o\" | \"s\" | \"x\" | \"X\" | \"%\"\n",
    "    \"\"\"\n",
    "    # 例子:\n",
    "        '={0:10} = {1:10}'.format('spam', 123.456)    # 输出'=spam       =    123.456'\n",
    "        '={0:>10}='.format('test')                    # 输出'=      test='\n",
    "        '={0:<10}='.format('test')                    # 输出'=test      ='\n",
    "        '={0:^10}='.format('test')                    # 输出'=   test   ='\n",
    "        '{0:X}, {1:o}, {2:b}'.format(255, 255, 255)   # 输出'FF, 377, 11111111'\n",
    "        'My name is {0:{1}}.'.format('Fred', 8)       # 输出'My name is Fred    .'  动态指定参数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 内置字符串处理函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#-- 内置str处理函数：\n",
    "    str1 = \"stringobject\"\n",
    "    # 全部大写，全部小写、大小写转换，首字母大写，每个单词的首字母都大写\n",
    "    str1.upper(); str1.lower(); str1.swapcase(); str1.capitalize(); str1.title()        \n",
    "    str1.ljust(width)                       # 获取固定长度，左对齐，右边不够用空格补齐\n",
    "    str1.rjust(width)                       # 获取固定长度，右对齐，左边不够用空格补齐\n",
    "    str1.center(width)                      # 获取固定长度，中间对齐，两边不够用空格补齐\n",
    "    str1.zfill(width)                       # 获取固定长度，右对齐，左边不足用0补齐\n",
    "    str1.find('t',start,end)                # 查找字符串，可以指定起始及结束位置搜索\n",
    "    str1.rfind('t')                         # 从右边开始查找字符串\n",
    "    str1.count('t')                         # 查找字符串出现的次数\n",
    "    #上面所有方法都可用index代替，不同的是使用index查找不到会抛异常，而find返回-1\n",
    "    str1.replace('old','new')               # 替换函数，替换old为new，参数中可以指定maxReplaceTimes，即替换指定次数的old为new\n",
    "    str1.strip();                           # 默认删除空白符\n",
    "    str1.strip('d');                        # 删除str1字符串中开头、结尾处，位于 d 删除序列的字符\n",
    "    str1.lstrip();\n",
    "    str1.lstrip('d');                       # 删除str1字符串中开头处，位于 d 删除序列的字符\n",
    "    str1.rstrip();\n",
    "    str1.rstrip('d')                        # 删除str1字符串中结尾处，位于 d 删除序列的字符\n",
    "    str1.startswith('start')                # 是否以start开头\n",
    "    str1.endswith('end')                    # 是否以end结尾\n",
    "    # 判断字符串是否全为字符、数字、小写、大写\n",
    "    str1.isalnum(); str1.isalpha(); str1.isdigit(); str1.islower(); str1.isupper()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 用Print方式输出查看\n",
    "str1 = \"stringObject\"\n",
    "print(str1.upper(),str1.lower())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习：\n",
    "一个5位数，判断它是不是回文数。即12321是回文数，个位与万位相同，十位与千位相同"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x = '12321'\n",
    "flag = True\n",
    " \n",
    "for i in range(???):\n",
    "    if x[i] ??? x[-i - 1]:\n",
    "        flag = False\n",
    "        ???\n",
    "if flag:\n",
    "    print(???)\n",
    "else:\n",
    "    print(???)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个<strong>6</strong>位数，判断它是不是回文数。即12321是回文数，个位与万位相同，十位与千位相同"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 自己完成，尽量简洁\n",
    "x = '123321'\n",
    "if ???:\n",
    "    print(\"%d 是回文数\" % int(x))\n",
    "else:\n",
    "    print(\"%d 不是回文数\" % int(x))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
